package com.lixiaoyi.config.security.handle;


import com.alibaba.fastjson.JSON;
import com.lixiaoyi.config.exception.CustomerAuthenticationException;
import com.lixiaoyi.utils.Result;
import com.lixiaoyi.utils.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 李小毅
 * @Description
 * @Date 2022-07-01
 */

// 登录认证失败处理器
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 定义变量 保存异常信息
        String message = null;
        // 定义状态码  错误编码
        int code = 500;

        // 判断异常类型
        if (exception instanceof AccountExpiredException){
            message = "账户过期，登陆失败";
        }else if (exception instanceof BadCredentialsException){
            message = "用户名或密码错误，登陆失败";
        }else if (exception instanceof CredentialsExpiredException){
            message = "密码过期，登陆失败";
        }else if (exception instanceof DisabledException){
            message = "账户被禁用，登陆失败";
        }else if (exception instanceof LockedException){
            message = "账户被锁，登陆失败";
        }else if (exception instanceof InsufficientAuthenticationException){
            message = "账户不存在，登陆失败";
        }else if (exception instanceof CustomerAuthenticationException){
            message = exception.getMessage() ;
            code = 600;
        }
        else {
            message = "登陆失败";
        }
        // 将结果转成JSON格式
        String result = JSON.toJSONString(Result.error().code(ResultCode.ERROR).message(message));
        // 输出并关闭流
        outputStream.write(result.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}









